﻿using System;
using System.IO;
using System.Collections;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Printing;
using SharppiFlowEditor.models;
using SharppiFlowEditor.views;
using System.Windows.Forms;

namespace SharppiFlowEditor.controllers
{
    public class AppController : AbstractController
    {
        // Model and view for the controller
        //private AppModel model;
        //private AppView view;

        public AppController(AppView appView, AppModel appModel)
        {
            Model = appModel;
            View = appView;
        }


        public void NewDocument_Click(object sender, EventArgs e)
        {
            NewDocumentView dialog = new NewDocumentView();
            dialog.ShowDialog(View);

            if (dialog.DialogResult == DialogResult.OK)
            {
                //Document doc = Model.NewDocument(null, dialog.DiagramWidth, dialog.DiagramHeight);
                //View.document.GraphDocument = doc;
                // set the initial controller
                View.document.Controller = View.newC;
                View.newC.newDocoment(dialog.DiagramWidth, dialog.DiagramHeight);
                View.document.Location = new Point(0, 0);
                // set attributes of the diagramview ui component
                View.document.Dock = DockStyle.None;
                View.document.NodeBrush = new SolidBrush(Color.Yellow);
                // set event handler for changing the controller
                
                View.document.Focus();
                View.document.DiagramViewSize = new Size(dialog.DiagramWidth, dialog.DiagramHeight);
                View.setDiagramVisible(true);
            }
            else if (dialog.DialogResult == DialogResult.Cancel)
            {

            }
            View.document.Invalidate();
            View.document.Update();
        }

        public void OpenDocument_Click(object sender, EventArgs e)
        {
            //AppController previous = view.Controller
            Stream stream = null;
            OpenFileDialog openFileDialog = new OpenFileDialog();

            DiagramController previousCtrl = View.document.Controller;

            openFileDialog.InitialDirectory = "c:\\";
            openFileDialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*";
            openFileDialog.FilterIndex = 2;
            openFileDialog.RestoreDirectory = true;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
               // try
               // {
                    if ((stream = openFileDialog.OpenFile()) != null)
                    {
                        View.setDiagramVisible(true);
                        View.document.Controller = View.openC;
                        View.openC.Open(stream);
                    }
                /*}
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                } */
            }

            View.document.Controller = previousCtrl;
        }

        public void SaveDocument_Click(object sender, EventArgs e)
        {
            if (View.document.GraphDocument.SaveFilePath == "")
            {
                SaveAsDocument_Click(sender, e);
            }
            else
            {
                ((SaveDocumentController)View.saveC).Save(View.document.GraphDocument.SaveFilePath);
            }
        }

        public void SaveAsDocument_Click(object sender, EventArgs e)
        {
            //Stream stream;
            string filePath;
            SaveFileDialog saveDialog = new SaveFileDialog();

            saveDialog.Filter = "xml files (*.xml)|*.xml";
            saveDialog.FilterIndex = 2;
            saveDialog.RestoreDirectory = true;

            if (saveDialog.ShowDialog() == DialogResult.OK)
            {
                if ((filePath = saveDialog.FileName) != null)
                {
                    ((SaveDocumentController)View.saveC).Save(filePath);
                    //stream.Close();
                }
            }     
        }

        public void PrintDocument_Click(object sender, EventArgs e)
        {
            PrintDialog printDialog = new PrintDialog();
            PrintDocument printDocument = new PrintDocument();

            if (printDialog.ShowDialog() == DialogResult.OK)
            {
                PrinterSettings values;
                values = printDialog.PrinterSettings;
                printDialog.Document = printDocument;
                printDocument.PrintPage += PrintDocument;
                printDocument.PrintController = new StandardPrintController();
                printDocument.Print();
            }
            printDocument.Dispose();
        }

        public void DocumentOverview_Click(object sender, EventArgs e)
        {
            PrintPreviewDialog printOverview = new PrintPreviewDialog();
            PrintDocument printDocument = new PrintDocument();

            printOverview.Document = printDocument;
            printDocument.OriginAtMargins = true;
            printDocument.PrintPage += PrintDocument;
            printOverview.ShowDialog();     
        }

        public void ExitApp_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        public void EditToolButton_Click(object sender, EventArgs e)
        {
            View.document.Controller = View.editC;
            //editC.View = this.view;
            View.changeHeadline("Select/move elements mode");
        }

        public void MoveNodeToolButton_Click(object sender, EventArgs e)
        {
            View.document.Controller = View.selC;
            //selC.View = this.view;
            View.changeHeadline("Select/move elements mode");
        }

        public void EraserToolButton_Click(object sender, EventArgs e)
        {
            View.document.Controller = View.delC;
            //delC.View = this.view;
            View.changeHeadline("Delete nodes/connectors mode");
        }

        public void ConnectorToolButton_Click(object sender, EventArgs e)
        {
            View.document.Controller = View.connC;
            //connC.View = this.view;
            View.changeHeadline("Connect nodes mode");
        }

        public void AddNodeToolButton_Click(object sender, EventArgs e)
        {
            View.document.Controller = View.nodeC;
            //nodeC.View = this.view;
            View.changeHeadline("Create nodes mode");
        }

        public void SnapToGridButton_Click(object sender, EventArgs e)
        {
            ToolStripButton button = (ToolStripButton)sender;
            
            if (button.Checked)
            {
                View.document.GraphDocument.SnapToGridState = true;
                View.diagramToolBar.snapToGridSizeLabel.Enabled = true;
                View.diagramToolBar.snapToGridSizeComboBox.Enabled = true;
                button.Text = "Snap to grid: on";
            }
            else
            {
                View.document.GraphDocument.SnapToGridState = false;
                View.diagramToolBar.snapToGridSizeLabel.Enabled = false;
                View.diagramToolBar.snapToGridSizeComboBox.Enabled = false;
                button.Text = "Snap to grid: off";
            }

            View.Invalidate();
            View.Update();
            View.document.Invalidate();
            View.document.Update();
        }

        public void SnapToGridSizeComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            ToolStripComboBox box = (ToolStripComboBox)sender;
            int itemValue = int.Parse(box.SelectedItem.ToString());

            View.document.GraphDocument.GridWidth = itemValue;
        }

        public void ChangeController(object sender, KeyEventArgs e)
        {

            if (Control.ModifierKeys == Keys.Control)
            {
                switch (e.KeyCode)
                {
                    case Keys.D1:
                        View.document.Controller = View.nodeC;
                        View.changeHeadline("Create nodes mode");
                        break;
                    case Keys.D2:
                        View.document.Controller = View.connC;
                        View.changeHeadline("Connect nodes mode");
                        break;
                    case Keys.D3:
                        View.document.Controller = View.delC;
                        View.changeHeadline("Delete nodes/connectors mode");
                        break;
                    case Keys.D4:
                        View.document.Controller = View.editC;
                        View.changeHeadline("Select/move elements mode");
                        break;
                }
            }
        }

        public void PrintDocument(object sender, PrintPageEventArgs e)
        {
            Bitmap memoryImage = new Bitmap(View.document.DiagramViewSize.Width, View.document.DiagramViewSize.Height);
            //view.document.DrawToBitmap(memoryImage, view.document.ClientRectangle);
            View.document.DrawToBitmap(memoryImage, new Rectangle(0, 0, memoryImage.Width, memoryImage.Height));
            e.Graphics.DrawImage(memoryImage, 0, 0);
        }

        public void ExportDocumentImage_Click(object sender, EventArgs e)
        {
            Bitmap memoryImage = new Bitmap(View.document.DiagramViewSize.Width, View.document.DiagramViewSize.Height);
            View.document.DrawToBitmap(memoryImage, new Rectangle(0, 0, memoryImage.Width, memoryImage.Height));
            //e.Graphics.DrawImage(memoryImage, 0, 0);

            Graphics image = Graphics.FromImage(memoryImage);

            Brush b = Brushes.White;

            //Stream stream;
            string filePath;
            SaveFileDialog saveDialog = new SaveFileDialog();

            saveDialog.Filter = "jpg files (*.jpg)|*.jpg";
            saveDialog.FilterIndex = 2;
            saveDialog.RestoreDirectory = true;

            if (saveDialog.ShowDialog() == DialogResult.OK)
            {
                if ((filePath = saveDialog.FileName) != null)
                {
                    Model.exportImage(memoryImage, filePath);
                    //((SaveDocumentController)View.saveC).Save(filePath);
                    //stream.Close();
                }
            }   

            
        }

    }
}
